﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Procure.Data.Context;
using umbraco.uicontrols;

namespace Procure.Web.order
{
    public partial class editOrder : System.Web.UI.Page
    {
        #region OnInit
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            MenuImageButton save = UmbracoPanel2.Menu.NewImageButton();
            save.ImageUrl = umbraco.GlobalSettings.Path + "/images/editor/save.gif";
            save.AlternateText = "Save";

            save.Click += new ImageClickEventHandler(save_Click); ;
        } 
        #endregion

        #region Page_Load
        protected void Page_Load(object sender, EventArgs e)
        {
            // only load the order if this isn't a postback
            if (!IsPostBack)
            {
                // find the id from the query string
                string orderid = Request["id"];
                int OrderId = 0;
                // try to pase the id into an int
                if (int.TryParse(orderid, out OrderId))
                {
                    // load the order
                    LoadOrder(OrderId);
                }
            }

        } 
        #endregion

        #region LoadOrder
        private void LoadOrder(int OrderId)
        {
            ProcureDataContext context = DataFactory.GetDataContext();
            Order order = context.Orders.FirstOrDefault(o => o.Id == OrderId);
            if (order != null)
            {
                // find a list of status where global is true, or the status is the next move to status
                var statusList = from s in context.Status
                                 where s.Global == true
                                        || s.Id == order.Status.MoveToStatusId
                                        || s.Id == order.StatusId
                                 orderby s.Name
                                 select s;
                // populate the order details
                OrderedOn.Text = order.OrderedOn.ToString();
                Username.Text = order.User.Username;

                // populate the status list
                OrderStatus.DataSource = statusList;
                OrderStatus.DataBind();
                // set the currently selected status
                OrderStatus.SelectedValue = order.StatusId.ToString();

                // set the list of products in the current order as the data source
                ProductsList.DataSource = order.OrderProducts;
                // bind the productslist ListView
                ProductsList.DataBind();

                // check and see if the next status in the flow is populated
                if (order.Status.MoveToStatusId.HasValue)
                {
                    // if so, load up a status object for it
                    Status moveToStatus = context.Status.FirstOrDefault(s => s.Id == order.Status.MoveToStatusId.Value);
                    // as long as a status object was found
                    if (moveToStatus != null)
                        // display the name of the "happy path" status to move to
                        NextStatus.Text = string.Format("(Next Status: {0})", moveToStatus.Name);
                }
            }
        } 
        #endregion

        protected void ChangeStatus_Click(object sender, EventArgs e)
        {
        }

        #region save_Click
        void save_Click(object sender, ImageClickEventArgs e)
        {
            // find the order id from the URL
            int id = int.Parse(Request["id"]);
            // get an instance of the data context
            ProcureDataContext context = DataFactory.GetDataContext();

            // get the new status id from the status drop down
            int newStatusId = Convert.ToInt32(OrderStatus.SelectedValue);
            // retrieve a status object for that status id
            Status newStatus = context.Status.FirstOrDefault(s => s.Id == newStatusId);

            // load up the order based on the order id retrieved from the URL
            Order order = context.Orders.FirstOrDefault(cs => cs.Id == id);
            // if the order status changed, then execute the following block
            if (order.StatusId != newStatusId)
            {
                // change the status on the order object
                order.StatusId = newStatus.Id;
                // create a new order status history entry
                OrderStatusHistory history = new OrderStatusHistory();
                // assign it the current order
                history.Order = order;
                // assign it the new status
                history.Status = newStatus;
                // populate the current date/time onto the history item
                history.MovedToOn = DateTime.Now;
                // log the current user as changing the status
                history.MovedToBy = User.Identity.Name;
                // add the new history object to the current order
                order.OrderStatusHistories.Add(history);
            }

            // submit any changes
            context.SubmitChanges();

            // reload the current order
            LoadOrder(id);
        } 
        #endregion
    }
}
